import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'app',
    component: () => import('@/views/layout/index'),
    redirect: '/home',
    children: [{
      path: 'home',
      component: () => import('@/views/home/home')
    },
    {
      path: 'userM',
      name: 'userManage',
      component: () => import('@/views/adminManage/userM')
    },
    {
      path: 'adminM',
      name: 'adminManage',
      component: () => import('@/views/adminManage/adminM')
    },
    {
      path: 'book',
      name: 'Book',
      component: () => import('@/views/book/index')
    },
    {
      path: 'messgae',
      name: 'Message',
      component: () => import('@/views/message/index')
    },
    {
      path: 'cc',
      name: 'cc',
      component: () => import('@/views/cc')
    },
    {
      path: '/paymanage',
      name: 'Paymanage',
      component: () => import('@/views/payManage/payManage')
    },
    {
      path: '/article',
      name: 'Article',
      component: () => import('@/views/article/article')
    },

    {
      path: '/hotelist',
      name: 'Hotelist',
      component: () => import('@/views/hotelManage/hotelList')
    },
    {
      path: '/roomList',
      name: 'RoomList',
      component: () => import('@/views/hotelManage/roomManage/roomList')
    },
    {
      path: '/addroom',
      name: 'Addroom',
      component: () => import('@/views/hotelManage/roomManage/addRoom')
    }
    ]

  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index')
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/reg'] // 路由白名单
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userinfo.username) {
      // 登录时发现vuex里没有用户信息并且有token才会发送请求
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    // 未登录,跳转到登陆界面
    if (whiteList.includes(to.path)) {
      // 数组.includes(值),作用:判断值是否在数组里出现过,出现过原地返回true
      next()
    } else {
      // next强制切换到登录路径,会再次走了有==路由守卫再去匹配路由表
      next('/login')
    }
  }
})
export default router
